package com.axxc.jpa.task.rabbitmsg.provider;

import java.util.Random;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

import com.axxc.jpa.entity.TestPersonEntity;
import com.axxc.jpa.event.TestEvent;
import com.axxc.jpa.repository.ITestPersonEntityRepository;

/**
 * 
 * @ClassName: RabbitMqEnumEntityMsgProviderTask
 * @Description: 测试含枚举的实体
 * @author xxc
 * @date 2018年8月10日 上午10:54:41
 * @see Cron表达式{@link http://www.pppet.net/}
 */
// @Component
public class RabbitMqTestPersonEntityMsgProviderTask {

	private static final Random radnom = new Random();

	private static final int PROVIDER_COUNT = 1000;// 每分钟随机产生条数

	@Autowired
	private ApplicationContext applicationContext;

	@Autowired
	private ITestPersonEntityRepository testPersonEntityRepository;

	@Autowired
	private AmqpTemplate rabbitTemplate;

	// @Async
	// @Scheduled(cron = "0 0/1 * * * *") // corn表达式
	public void insert() {
		TestPersonEntity t;
		int nextInt = radnom.nextInt(PROVIDER_COUNT);
		for (int i = 0; i < nextInt; i++) {
			t = new TestPersonEntity();
			t.setPersonName("熊骑士" + i);
			this.rabbitTemplate.convertAndSend("test_person", t);
		}
	}

	// @Async
	// @Scheduled(cron = "0 0/17 * * * *") // Corn表达式
	public void remove() {
		int id = radnom.nextInt(20000);
		this.testPersonEntityRepository.delete(id * 1L);
	}

	@Async
	@Scheduled(cron = "30 0/1 * * * *") // Corn表达式
	public void update() {
		Long id = radnom.nextInt(2000) * 1L;
		TestPersonEntity t = this.testPersonEntityRepository.findOne(id);
		if (null != t) {
			t.setPersonName("详解Java-Persistence-api");
			this.rabbitTemplate.convertAndSend("test_person", t);
			this.applicationContext.publishEvent(new TestEvent(t, "修改了名称"));
		} else {
			// id = 1L;
			// while (t == null) {
			// t = this.testPersonEntityRepository.findOne(id);
			// id++;
			// }
			this.applicationContext.publishEvent(new TestEvent(id, "该对象不存在"));
		}
	}

}
